package com.xiaoyang.forum.service.impl;

import com.xiaoyang.forum.common.code.ResultCode;
import com.xiaoyang.forum.common.exception.ApplicationException;
import com.xiaoyang.forum.domain.dto.ArticleDTO;
import com.xiaoyang.forum.domain.dto.UserUpdateDTO;
import com.xiaoyang.forum.domain.pojo.Article;
import com.xiaoyang.forum.domain.pojo.User;
import com.xiaoyang.forum.domain.vo.ArticleVO;
import com.xiaoyang.forum.domain.vo.UserVO;
import com.xiaoyang.forum.mapper.ArticleMapper;
import com.xiaoyang.forum.mapper.UserMapper;
import com.xiaoyang.forum.service.IAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: XiaoYang
 * @CreateTime: 2025-09-22
 * @Description:
 */
@Slf4j
@Service
public class AdminServiceImpl implements IAdminService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 获取用户列表
     * @return
     */
    @Override
    public List<UserVO> userList() {
        log.info("获取用户列表");

        return userMapper.selectUserList();
    }

    /**
     * 修改用户状态
     * @param userUpdateDTO
     * @return
     */
    @Override
    public int updateUserStatus(UserUpdateDTO userUpdateDTO) {
        log.info("修改用户状态");
        User user = userMapper.selectById(userUpdateDTO.getId());
        if (user == null) {
            log.info("用户不存在");
            throw new ApplicationException(ResultCode.FAILED_USER_NOT_EXISTS.getMessage());
        }
        if (user.getState() == 1) {
            log.info("用户解除禁言" + userUpdateDTO.getId());
            user.setState(0);
        } else {
            log.info("用户禁言" + userUpdateDTO.getId());
            user.setState(1);
        }
        return userMapper.updateById(user);
    }

    /**
     * 获取文章列表
     * @return
     */
    @Override
    public List<ArticleVO> articleList() {
        log.info("获取文章列表");

        return articleMapper.selectArticleList();
    }

    /**
     * 审核帖子
     * @param articleDTO
     * @return
     */
    @Override
    public int updateArticleStatus(ArticleDTO articleDTO) {
        log.info("审核帖子");
        Article article = articleMapper.selectById(articleDTO.getId());
        if (article == null) {
            log.info("文章不存在");
            throw new ApplicationException(ResultCode.FAILED_ARTICLE_NOT_EXISTS.getMessage());
        }

        article.setState(1); // 审核通过
        return articleMapper.updateById(article);
    }
}
